package com.hlk.hlk_blog.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hlk.hlk_blog.entity.*;
import com.hlk.hlk_blog.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;


import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class IndexController {
    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;
    @Autowired
    private CommentService commentService;
    //@value引用这个图片,在appliaction.yml里配置
    @Value("${comment.avatar}")
    private String avatar;


    @GetMapping("/")
    public String index(@RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum, Model model) {//Long tagId
        PageHelper.startPage(pageNum, 5);
        List<Blog> blogList = blogService.listblog();
        List<Blog> recommendBlogs = blogService.getAllRecommendBlog(5);
        PageInfo<Blog> pageInfo = new PageInfo<>(blogList);
        List<Type> types = typeService.findType(5);
        //遍历所有分类通过typeId查询该分类有多少blog
        for (Type type : types) {
            type.setBlogs(blogService.getBlogByTypeId(type.getId()));
        }
        List<Tag> tags = tagService.findTag(9);
        //遍历所有标签通过typeId查询该分类有多少blog
        for (Tag tag : tags) {
            tag.setBlogs(blogService.getBlogByTagId(tag.getId()));
        }
        //最新博客
       /* List<Blog> newblogs = blogService.newblog(4);
        model.addAttribute("newblogs",newblogs);*/
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("types", types);
        model.addAttribute("tags", tags);
        model.addAttribute("recommendBlogs", recommendBlogs);
        return "index";

    }

    /**
     * 最新blog
     */
    @GetMapping("/footer/newblog")
    public String newblogs(Model model) {
        //前台获取推荐博客
        List<Blog> newblogs = blogService.newblog(4);
        model.addAttribute("newblogs", newblogs);
        return "_fragments :: newblogs";
    }

    /*-----------------------------------------------*/
//博客详情
    @GetMapping("/blog/{id}")
    public String showBlog(@PathVariable("id") Long id, Model model) {
        Blog blog = blogService.findBlogById(id);
        model.addAttribute("blog", blog);
        return "blog";
    }

    //加载评论
    @GetMapping("/comments")
    public String comments(Long blogId, Model model) {
        List<Comment> comments = commentService.findListByBlogId(blogId);
        model.addAttribute("comments", comments);
        return "blog :: commentList";
    }

    @PostMapping("/comments")
    public String input(Comment comment, Model model, HttpSession session) {
        Long blogId = comment.getBlog().getId();

        User user = (User) session.getAttribute("user");
        System.out.println(user);
        if (user != null) {
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        } else {
            comment.setAvatar("/images/avatar.png");
            comment.setAdminComment(false);
        }
        System.out.println(comment);
        commentService.addComment(comment);
        return "redirect:/comments?blogId=" + blogId;
    }


    /*----------------------------------------------*/
    //点击分类进入分类页
    @GetMapping("/types/{id}")
    public String getBlogByType(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum, @PathVariable("id") Long id, Model model) {
        /*头部分类展示*/
        //获取所有type并获取所有type关联的blog
        List<Type> types = typeService.getAllType();
        for (Type type : types) {
            type.setBlogs(blogService.getBlogByTypeId(type.getId()));
        }
        //当id=-1时展示分类下最多博客
        if (id == -1) {
            //id=-1时分类下最多博客的typeid
            id = typeService.getMaxTypeId();
        }
        PageHelper.startPage(pageNum, 5);
        List<Blog> blogs = blogService.getBlogByTypeId(id);
        //把blogs集合按照updatetime倒叙排列
        Collections.sort(blogs, new Comparator<Blog>() {
            @Override
            public int compare(Blog o1, Blog o2) {
                Date date1=o1.getUpdateTime();
                Date date2=o2.getUpdateTime();
                if(date1.getTime()>date2.getTime()){
                    return -1;
                }else if(date1.getTime()<date2.getTime()){
                    return 1;
                }else {
                    return 0;
                }
            }
        });
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs);
        model.addAttribute("types", types);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("activeTypeId", id);
        return "types";
    }

    //标签页
    @GetMapping("/tags/{id}")
    public String getBlogByTag(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum, @PathVariable("id") Long id, Model model) {
        /*头部分类展示*/
        //获取所有type并获取所有tag关联的blog
        List<Tag> tags = tagService.getAllTags();
        for (Tag tag : tags) {
            tag.setBlogs(blogService.getBlogByTagId(tag.getId()));
        }
        //如果通过首页的标签按钮id=-1，把id赋值为标签
        if (id == -1) {
            id = tagService.getMaxTagId();
        }
        /*
         * 自定义的sql如果不需要用pageHerlper插件分页，不要放到紧跟着pageHelper后面。
         * PageHelper后面紧跟的会自定义个limit执行分页*/
        PageHelper.startPage(pageNum, 5);
        List<Blog> blogs = blogService.getBlogByTagId(id);
        Collections.sort(blogs, new Comparator<Blog>() {
            @Override
            public int compare(Blog o1, Blog o2) {
                Date dat1 = o1.getUpdateTime();
                Date dat2 = o2.getUpdateTime();
                if(dat1.getTime()>dat2.getTime()){
                    return -1;
                }else if(dat1.getTime()<dat2.getTime()){
                    return 1;
                }else {
                    return 0;
                }
            }
        });
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs);
        model.addAttribute("tags", tags);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("activeTagId", id);
        return "tags";
    }

    //跳转关于我页面
    @GetMapping("/about")
    public String showAboutMe() {
        return "about";
    }

    @GetMapping("archives")
    public String archives(Model model) {
        List<String> years = blogService.getblogYear();
        Map<String, List<Blog>> map = new LinkedHashMap<>();
        for (String year : years) {
            map.put(year, blogService.getBlogByYear(year));
        }
        Long blogCount = blogService.getBlogCount();
        model.addAttribute("archiveMap", map);
        model.addAttribute("blogCount", blogCount);
        return "archives";
    }

    //搜索
    @PostMapping("/search")
    public String search(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                         @RequestParam String query, Model model) {
        PageHelper.startPage(pageNum, 5);
        List<Blog> blogs = blogService.searchIndexBlog(query);
        PageInfo pageInfo = new PageInfo<>(blogs);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("query", query);
        return "search";
    }

}
